package com.lagou.edu.controller;

import com.lagou.edu.service.ClientService;
import com.lagou.edu.service.CodeFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/user")
public class ClientController {


    @Autowired
    private ClientService clientService;
    @Autowired
    private CodeFeign codeFeign;

    @RequestMapping("/login")
    public ModelAndView loginPage(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("login");
        return mv;
    }

    @RequestMapping("/register")
    public ModelAndView registerPage(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("register");
        return mv;
    }


    // 获取验证码
    @RequestMapping("/createcode")
    public ModelAndView createCode(String email){

        ModelAndView mv = new ModelAndView();
        String code = codeFeign.sendCode(email);
        mv.setViewName("register");
        mv.addObject("havecode",code);
        return mv;
    }


    // 注册验证一下验证码是否正确
    @RequestMapping("/clientregister")
    public String ClientRegister (String email, String pwd, String code){

        // 1.取出email对应的验证码匹配一下
        String status = codeFeign.validate(email, code); // success,error

        if (status.equals("success")) {

            clientService.saveEmailToken(
                    email, clientService.generateToken(email, pwd)
            );
            return "注册成功！";
        }else {
            return "注册失败！";
        }

    }

    @RequestMapping("/clientlogin")
    public String clientlogin (String email, String pwd){

        String token = clientService.validateUser(email, pwd);
        System.out.println("========================================="+token);
        if(token.equals("success")){

            return  "登录成功";
        }else{
            return "登录失败";
        }
    }
}
